package com.lu.security.mac;

import com.lu.security.tools.HexTools;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * author: luqihua
 * date:2023/3/28
 * description: 哈希运算消息认证码
 **/
public class HMacTools {
    private static final String ENCODING = "UTF-8";

    /**
     * @param text     待哈希的字符串
     * @param password 运算秘钥
     * @return 返回哈希运算后的base64的字符串
     * @throws Exception
     */
    public static String hMacMD5(String text, String password) throws Exception {
        Mac mac = Mac.getInstance("HmacMD5");
        //第一个参数可以是任意字符串,第二个参数与获取Mac对象的algorithm相同
        mac.init(new SecretKeySpec(password.getBytes(ENCODING), "HmacMD5"));
        byte[] bytes = mac.doFinal(text.getBytes(ENCODING));
        return HexTools.encodeToBase64(bytes).toUpperCase();
    }

    /**
     * @param text     待哈希的字符串
     * @param password 运算秘钥
     * @return 返回哈希运算后的base64的字符串
     * @throws Exception
     */
    public static String hMacSHA1(String text, String password) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(password.getBytes(ENCODING), "HmacSHA1"));
        byte[] bytes = mac.doFinal(text.getBytes(ENCODING));
        return HexTools.encodeToBase64(bytes).toUpperCase();
    }

}
